﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TvGuide.UI.Models;
using TVGuide.DataAccess;
using System.Web.Routing;
using System.Text.RegularExpressions;
using TVGuide.Common;
using System.Xml;

namespace TvGuide.UI.Controllers
{
    public class AdminController : BaseController
    {
        [HttpGet]
        public ActionResult Home()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Home(ExternalVideoModel model)
        {
            if (ModelState.IsValid)
            {
                long cat = (int)model.catEnum;
                model.Id = Utilsities.addExternalVideo(model.url, model.title, cat);
                var newUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
                model.newUrl = newUrl + Url.Action("Home", "Embed") + "?id=" + model.Id;
                
                return View(model);
            }
            return View(model);
        }

        public ActionResult VideosList()
        {
            var videos = Utilsities.getAllExternalVideos();
            List<ExternalVideoModel> model = new List<ExternalVideoModel>();
            foreach (var item in videos)
            {
                model.Add(new ExternalVideoModel()
                {
                    Id = item.vidoId,
                    title = item.title,
                    url = item.url,
                    views = item.views,
                });
            }
            return View(model);
        }

    }


    public class EmbedController : Controller
    {
        
        public ActionResult Home(ExternalVideoModel model)
        {
            var video = Utilsities.getExternalVideoWithIncmnt(model.Id);
            string url = "";
            string pageUrl = "http://tvcuyc.am/arm/Embed?id=" + model.Id;
            ViewData["pageUrl"] = pageUrl;
            ViewData["videoTitle"] = "Click to watch the video";
         
            if (video != null)
            {
                url = video.url;
                string titleInfo = "";
                string img = "";
                string title = "";
                string desc = "";
                if (url.Contains("youtube"))
                {
                    Regex YoutubeVideoRegex = new Regex(@"youtu(?:\.be|be\.com)/embed/(.+)", RegexOptions.IgnoreCase);
                    Match youtubeMatch = YoutubeVideoRegex.Match(url);
                    var videoId = youtubeMatch.Groups[1].Value;
                    img = "http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg";
                    ViewData["tubImgUrl"] = img;
                    ViewData["swfUrl"] = "http://www.youtube.com/v/" + videoId + "?version=3&amp;autohide=1";
                    titleInfo = "http://gdata.youtube.com/feeds/api/videos?v=2&q=" + videoId + "&max-results=1&prettyprint=true";
                    string infoData = TVGuide.Parser.HTTPClient.GetSiteContent(titleInfo, System.Text.Encoding.UTF8, "");
                    Regex titleExp = new Regex("<entry.*<title>([^<>]*)</title>", RegexOptions.IgnoreCase);
                    Regex descExp = new Regex("<media:description type='plain'>(.*)</media:description>", RegexOptions.IgnoreCase);
                    title = titleExp.Match(infoData).Groups[1].Value;
                    desc = descExp.Match(infoData).Groups[1].Value;
                }
                if (url.Contains("rutube"))
                {
                    try
                    {
                        var RutubeVId = video.url.Split('/')[3];
                        string apiUrl = "http://rutube.ru/api/oembed/?url=http://rutube.ru/video/" + RutubeVId + "/&format=xml";
                        XmlDocument xmldoc = new XmlDocument();
                        xmldoc.Load(apiUrl);
                        XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable);
                        XmlNode nListImg = xmldoc.SelectSingleNode("/root/thumbnail_url", xnm1);
                        XmlNode nListTitle = xmldoc.SelectSingleNode("/root/title", xnm1);
                        img = nListImg.InnerText;
                        ViewData["tubImgUrl"] = img;
                        ViewData["swfUrl"] = "http://www.rutube.ru/" + RutubeVId;
                        title = nListTitle.InnerText;

                    }
                    catch (Exception ex) { }  
                }
                
                if (desc.Length > 160)
                {
                    desc = desc.Substring(0, 157)+"...";
                }
                if (video.title==null)
                {
                    ViewData["videoTitle"] = title;
                }
                else
                {
                    ViewData["videoTitle"] = video.title;
                }
                
                ViewData["fbShare"] = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945&display=popup& link=" + pageUrl + "&  picture=" + img + "& name=" + title + "& caption=tvcuyc.am&  description=& redirect_uri=http://tvcuyc.am/close.html");
                ViewData["twitShare"] = HttpUtility.HtmlEncode("http://twitter.com/intent/tweet?text=I am going to watch " + "\"" + title +"\" "+pageUrl+ "&redirect_uri=http://tvcuyc.am/close.html");
                ViewData["desc"] = desc;

            }
            return View(new ExternalVideoModel() { url = url });
        }
    }
}
